include([
	'renderers.All'
    , 'world.Entity'
    , 'world.EntityImageAttachment'
	, 'com.unknown.GameWindow'
	, 'com.unknown.KeyboardHandler'
	, 'com.unknown.Room'
	, 'com.unknown.Sidebar'
	, 'com.unknown.Console'
	, 'HexGrid'
	, 'InputManager'
	, 'root'
	, 'Node'
	, 'EndlessGrid'
], function(){

	declare('init');
	
	var containers = [$('#floor-container'), $('#designer') ];
	
	inputManager = new InputManager();
	if( 'createTouch' in document ){
		var tid = new TouchInputDevice(inputManager, touchMask);
		tid.offset.x = -15;
		tid.offset.y = -30;
	}else{
		var mid = new MouseInputDevice(inputManager, touchMask);
		mid.offset.x = -15;
		mid.offset.y = -15;
	}
	keyboard1 = new KeyboardInputDevice(inputManager);

    var windowChanged = function(){
        touchMask.height = window.innerHeight-10;
        touchMask.width = window.innerWidth-10;

        canvasMask.height = window.innerHeight -40;
        canvasMask.width = window.innerWidth - 45;

        //console.log("Ready:")
        iterate(containers, function(item){
            var width = toNumber(item.css('padding-left')) || 0;
            width    += toNumber(item.css('padding-right')) || 0;
            width    += toNumber(item.css('margin-right')) || 0;
            width    += toNumber(item.css('margin-left')) || 0;
            width    += toNumber(item.css('left')) || 0;
            //width    += toNumber(item.css('right')) || 0;
            var height = toNumber(item.css('padding-top')) || 0;
            height    += toNumber(item.css('padding-bottom')) || 0;
            height    += toNumber(item.css('margin-top')) || 0;
            height    += toNumber(item.css('margin-bottom')) || 0;
            height    += toNumber(item.css('top')) || 0;
            //height    += toNumber(item.css('bottom')) || 0;
            console.log(item.attr('id') + "" + width + ", " + height);
            item.width(window.innerWidth - (10+width));
            item.height(window.innerHeight - (10+height));
        });
    };

    //See solution by brahn
    //http://stackoverflow.com/questions/2854407/javascript-jquery-window-resize-how-to-fire-after-the-resize-is-completed
    var eventSync = (function(){
        var timers = {};
        return function(callback, ms, uniqueId){
          if(!uniqueId){
              uniqueId = "Don't call this twice without a uniqueId";
          }
            if( timers[uniqueId]){
                clearTimeout(timers[uniqueId]);
            }
            timers[uniqueId] = setTimeout(callback, ms);
        };
    })();

    $(window).resize(function(){
        eventSync(windowChanged, 250, 'RESIZE_EVENT');
    });

	addOrientationChangedListener(windowChanged);
	
	room = new com.unknown.Room(roomUrl, '4dd85b36050615fbf8f54ffb', 'show');

	player = new world.Entity();
	player.attachments.push( new world.EntityImageAttachment('../images/characters/male_1_Walk.png') );
	player.attachments.push( new world.EntityImageAttachment('../images/characters/pants_Walk.png') );
	player.attachments.push( new world.EntityImageAttachment('../images/characters/hoodie_Walk.png') );	
    player.images = ['../images/characters/male_1_Walk.png', '../images/characters/pants_Walk.png', '../images/characters/hoodie_Walk.png'];
	player.name = username;
	gamewindow = new com.unknown.GameWindow(canvasMask, imagebucket);
    gamewindow.addEntity(player);
	gamewindow.renderers['std'] = new StandardRenderer();
	//gamewindow.renderers['debug'] = new WireFrameRenderer();
	//gamewindow.renderers['debug'] = new TriangleRenderer();
	
	analog1 = new AnalogStick(Quad.rectangle({x:0,y:0}, touchMask.width/2,touchMask.height));
	analog1.addListener(function(vector){
		player.inputChanged(vector);
	});
	inputManager.addListener("analog1", analog1);
	gamewindow.billboards.push(analog1);
	
	button1 = new Button(Quad.rectangle({x:touchMask.width/2, y:0}, touchMask.width, touchMask.height));
	button1.addListener(function(id){
		console.log("Activate!");
		player.activate();
	});
	inputManager.addListener("button1", button1);
	inputManager.addListener("keyboard", {
		onButtonDown : function(e){
			if( e.bId && e.bId.id == '13' ){
				player.activate();
			}
		}
	});
	gamewindow.billboards.push(button1);
	
	bus = new com.unknown.Console(consoleUrl);
	bus.connect();

	var cellLoader = function(cell, gridMeta, dir, x, y){
		var div = cell.div;
		var container = cell.container;
		if( container ){
			//console.log("Container removed: ");
			//console.log(dir);
			container.remove();
		}
		if( !gridMeta ){
			div.remove();
			return;
		}
		if( !div ){
			div = $(document.createElement('div'));	
		}		
		div._id = dir;
		div.addClass('loaded-cell');
		div.css('width', gridMeta.width);
		div.css('height', gridMeta.height);
		//div.css('border', 'solid black thin');
        //div.css('background-color', '#777');
		//div.addClass('edit-grid');
		div.css('margin', '0 0 0 0');
		div.css('padding', '0 0 0 0');
		div.css('position', 'absolute');
		var off = div.offset();
		off.left += x;
		off.top  += y;
		div.offset(off);
		
		cell.div = div;
		
		cell.container = $(document.createElement('div'));
		cell.container.css('position', 'relative');
		cell.container.css('left', '-1px');
		cell.container.css('top', '-8px')
		div.append( cell.container );

		//setTimeout(function(){
			room.load(cell, cell.roomId, dir);
		//}, 2);	
		
		$('#floor').append( div );
	};	
	
	eGrid = new EndlessGrid(canvasMask, cellLoader, {cellWidth:70, cellHeight:15, rowCount:20, colCount:5});
	eGrid.translate(0,0);
	gamewindow.entities["endless.grid"] = eGrid;

	gamewindow.start();

    $('#menuMask').load('menu/sidebar');

	window.scroll(1,1);

    include(['menus.ExitMenu']);
});